package com.dongdongshop.controller;

import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.api.UserServiceApi;
import com.dongdongshop.data.Result;
import com.dongdongshop.enums.ResultEnum;
import com.dongdongshop.service.AddressService;
import com.dongdongshop.util.JwtUtil;
import com.dongdongshop.util.LoginUser;
import com.dongdongshop.vo.AddressVO;
import com.dongdongshop.vo.AreasVO;
import com.dongdongshop.vo.CitiesVO;
import com.dongdongshop.vo.ProvincesVO;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("address")
public class AddressController {

    @Autowired
    private AddressService addressService;

    @Autowired
    private JwtUtil jwtUtil;


    @PostMapping("getAddressByUserId")
    public Result getAddressByUserId(@RequestHeader String AutharizeToken) {
        String userId = "";
        try {
            Claims claims = jwtUtil.parseJwt(AutharizeToken);
            LoginUser loginUser = JSONObject.parseObject(claims.getSubject(), LoginUser.class);
            userId = loginUser.getUserName();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.RESPOSE(ResultEnum.INVALID_TOKEN);
        }
        List<AddressVO> addressVOList = addressService.getAddressByUserId(userId);
        return Result.OK().setData(addressVOList);
    }

    @PostMapping("getAddressById")
    public Result getAddressById(@RequestParam Long addressId) {
        AddressVO addressVO = addressService.getAddressById(addressId);
        return Result.OK().setData(addressVO);
    }

    @GetMapping("getAllProvince")
    public Result getAllProvince() {
        List<ProvincesVO> list = addressService.getAllProvince();
        return Result.OK().setData(list);
    }

    @GetMapping("getAllCity")
    public Result getAllCity(@RequestParam String provinceId) {
        List<CitiesVO> list = addressService.getAllCity(provinceId);
        return Result.OK().setData(list);
    }

    @GetMapping("getAllArea")
    public Result getAllArea(@RequestParam String cityId) {
        List<AreasVO> list = addressService.getAllArea(cityId);
        return Result.OK().setData(list);
    }


    @PostMapping("addAddress")
    public Result addAddress(@RequestHeader String AutharizeToken,@RequestBody AddressVO addressVO) {
        Claims claims = jwtUtil.parseJwt(AutharizeToken);
        LoginUser loginUser = JSONObject.parseObject(claims.getSubject(), LoginUser.class);
        addressVO.setUserId(loginUser.getUserName());
        addressService.addAddress(addressVO);
        return Result.OK();
    }
}
